package com.lanou.student.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author zyj
 * @date 2022年06月01日 9:28
 */
public class ExcelUtil {

    public static Workbook getWorkbook(String fileName) {
        Workbook workbook = null;
        try {
            File file = new File(fileName);
            if (file.exists()) {
                workbook = new XSSFWorkbook(new FileInputStream(fileName));
            }else {
                workbook = new XSSFWorkbook();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    //获取Sheet页
    public static Sheet getSheet(Workbook workbook,String sheetname){
        Sheet sheet = workbook.getSheet(sheetname);
        if (null == sheet) {
            sheet = workbook.createSheet(sheetname);
        }

        return sheet;
    }



    public static Row getRow(Sheet sheet,int num){
        Row row = null;
        int first = sheet.getFirstRowNum();
        int last = sheet.getLastRowNum();
        row = sheet.getRow(num);
        if (num  == 0 || num < first || num > last) {
            row = sheet.createRow(num);
        }
        return row;
    }


    public static void setCellValue(Row row, Object ... objs){
        for (int i = 0; i < objs.length; i++) {
            row.createCell(i).setCellValue(String.valueOf(objs[i]));
        }

    }
}
